<template>
  <div class="container">
    <div class="search-line">
      <el-form :model="searchData" :inline="true">
        <el-form-item label="站点名称：">
          <el-input
            v-model="searchData.name"
            placeholder="请输入站点名称"
            autocomplete="off"
            @input="changeStationName"
          />
        </el-form-item>
        <el-form-item label="关联小区：">
          <el-select
            v-model="searchData.communityId"
            filterable
            remote
            :remote-method="remoteMethod"
            placeholder="请选择关联小区"
            style="width: 300px"
            clearable
            @change="selectByCommunityId"
          >
            <el-option
              v-for="item in communityOptions"
              :key="item.ID"
              :label="item.communityName"
              :value="item.ID"
            >
            </el-option>
          </el-select> </el-form-item
      ></el-form>

      <div class="right-btn">
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button @click="reset">重置</el-button>
      </div>
    </div>
    <div class="content">
      <div class="table-title">
        <span>站点列表</span>
        <el-button :icon="Plus" @click="openAddDialog" type="primary">
          新增站点
        </el-button>
      </div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="ID" label="小区ID" width="150px" />
        <el-table-column prop="stationName" label="小区名称" />
        <el-table-column prop="province" label="省份" />
        <el-table-column prop="city" label="市" />
        <el-table-column prop="area" label="区县" />
        <el-table-column prop="street" label="详细地址" />
        <!-- <el-table-column prop="status" label="营业状态">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
              @change="changeStatus(scope.row.status, scope.row.id)"
            >
            </el-switch>
          </template>
        </el-table-column> -->
        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <el-popconfirm
              title="确认删除该站点?"
              confirm-button-text="是"
              cancel-button-text="否"
              @confirm="deleteRow(scope.row.ID)"
            >
              <template #reference>
                <el-button link type="primary" size="small"> 删除 </el-button>
              </template>
            </el-popconfirm>
            <el-button
              link
              type="primary"
              size="small"
              @click.prevent="edit(scope.row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- <el-pagination
        class="my-pagination"
        :page-page="searchData.page"
        :page-size="searchData.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :background="true"
        layout="slot, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @page-change="handleCurrentChange"
      >
        <template #default>
          <span class="el-pagination__total is-first"> 共 {{ total }} 条 </span>
        </template></el-pagination
      > -->
    </div>
    <el-dialog
      v-model="dialogFormVisible"
      :title="id ? '新增站点' : '编辑站点'"
      width="500"
    >
      <el-form :model="form" ref="formRef" :rules="rules">
        <el-form-item label="站点名称" label-width="100px" prop="stationName">
          <el-input v-model="form.stationName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="关联小区" label-width="100px" prop="communityIds">
          <el-select
            v-model="form.communityIds"
            multiple
            filterable
            remote
            remote-show-suffix
            :remote-method="remoteMethod"
            placeholder="请选择"
            @change="changeSel"
          >
            <el-option
              v-for="item in communityOptions"
              :key="item.ID"
              :label="item.communityName"
              :value="item.ID"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" label-width="100px" prop="street">
          <el-input v-model="form.street" autocomplete="off" />
        </el-form-item>
        <el-form-item label="省份" label-width="100px" prop="province">
          <el-input v-model="form.province" autocomplete="off" />
        </el-form-item>
        <el-form-item label="市" label-width="100px" prop="city">
          <el-input v-model="form.city" autocomplete="off" />
        </el-form-item>
        <el-form-item label="区县" label-width="100px" prop="area">
          <el-input v-model="form.area" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { Plus, Lock } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import {
  getStaionList,
  getCommunityByName,
  addStation,
  delStationById,
  updateStation,
  getCommunityById,
} from "../../api/index";
import { ElMessage } from "element-plus";
const searchData = ref({
  page: 1,
  pageSize: 10,
  name: "",
  communityId: "",
});
const dialogFormVisible = ref(false);
const stataionId = ref();
const form = ref({
  communityIds: [],
  stationName: "",
  province: "",
  city: "",
  area: "",
  street: "",
});

const checkCommunityIds = (rule, value, callback) => {
  if (!value.length) {
    return callback(new Error("请输入小区名称"));
  } else {
    callback();
  }
};
const rules = ref({
  communityIds: [
    { validator: checkCommunityIds, trigger: "change" },
    { required: true },
  ],
  stationName: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
  street: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
});
const tableData = ref();
const total = ref(0);
const communityOptions = ref([]);
const page = ref(1);
const pageSize = ref(10);
const formRef = ref();
onMounted(() => {
  getALlTableData();
});

//按站点名称远程搜索站点
const remoteMethod = async (val) => {
  const res = await getCommunityByName({
    name: val,
    page: 1,
    pageSize: 100,
  });
  communityOptions.value = res.data;
};
//按站点名称查询
const getALlTableData = async (val) => {
  const params = {
    name: searchData.value.name,
    page: searchData.value.page,
    pageSize: searchData.value.pageSize,
  };
  const res = await getStaionList(params).catch();
  tableData.value = res.data;
  // total.value = res.data.length;
};

//下拉选择了小区，按小区code查询绑定的站点列表
const selectByCommunityId = async (id) => {
  searchData.value.name = "";
  const res = await getCommunityById({ id }).catch();
  tableData.value = res.data.stationList;
};
const changeStationName = async () => {
  searchData.value.communityId = "";
};
const search = async () => {
  searchData.value.communityId = "";
  getALlTableData();
};
const reset = async () => {
  searchData.value.name = "";
  searchData.value.communityId = "";
  getALlTableData();
};
const edit = async (obj) => {
  await remoteMethod();
  stataionId.value = obj.ID;
  dialogFormVisible.value = true;
  form.value.stationName = obj.stationName;
  form.value.province = obj.province;
  form.value.city = obj.city;
  form.value.area = obj.area;
  form.value.street = obj.street;
  form.value.communityIds = obj.communityList.map((item) => item.ID);
};

const openAddDialog = async () => {
  stataionId.value = "";
  dialogFormVisible.value = true;
};

const changeSel = async (val) => {
  console.log("communityIds", val);
};
const confirm = async () => {
  formRef.value.validate(async (valid, fields) => {
    if (valid) {
      if (stataionId.value) {
        //编辑
        const params = {
          communityIds: form.value.communityIds,
          station: {
            ID: stataionId.value,
            stationName: form.value.stationName,
            province: form.value.province,
            city: form.value.city,
            area: form.value.area,
            street: form.value.street,
          },
        };
        const res = await updateStation(params);
        stataionId.value = "";
        if (res.code === 200) {
          ElMessage({
            message: "操作成功",
            type: "success",
          });
          dialogFormVisible.value = false;
          getALlTableData();
        }
      } else {
        //新增
        const params = {
          communityIds: form.value.communityIds,
          station: {
            stationName: form.value.stationName,
            province: form.value.province,
            city: form.value.city,
            area: form.value.area,
            street: form.value.street,
          },
        };
        const res = await addStation(params);
        if (res.code === 200) {
          ElMessage({
            message: "操作成功",
            type: "success",
          });
          dialogFormVisible.value = false;
          getALlTableData();
        }
      }
      formRef.value.resetFields();
    }
  });
};
const handleSizeChange = async (val) => {
  console.log(val);
  getALlTableData();
};
const handleCurrentChange = async (val) => {
  console.log(val);
  getALlTableData();
};

//删除
const deleteRow = async (id) => {
  const res = await delStationById(id);
  if (res.code == 200) {
    getALlTableData();
    ElMessage({
      message: "操作成功",
      type: "success",
    });
    // if (tableData.value.length === 1) {
    //   if (searchData.value.page != 1) searchData.value.page--;
    getALlTableData();
    // }
  }
};
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
}
.search-line {
  display: flex;
  justify-content: space-between;
  padding: 10px 10px 0;
  .el-form-item {
    margin-bottom: 10px;
  }
}
.content {
  flex: 1;
  background-color: #fff;
  border-radius: 20px;
  padding: 10px;
  .table-title {
    display: flex;
    justify-content: space-between;
    font-weight: bold;
    font-size: 20px;
    border-bottom: 1px solid black;
    padding: 0 10px 10px;
    margin-bottom: 10px;
  }

  .my-pagination {
    padding: 10px 0 0 10px;
    display: flex;
    justify-content: center;
  }
}
</style>
